﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using SiGeSIB.Data.Common;

namespace SiGeSIB.GUI.Common
{
	public static class GUIExtensions
	{
		/// <summary>
		/// Retorna uma string idêntica à inicial, mas com a primeira letra de cada palavra na string convertida para maiúscula.
		/// </summary>
		/// <param name="text"></param>
		/// <returns></returns>
		public static string FirstToUpper(this string text)
		{
			string result = "";
			
			if(!string.IsNullOrEmpty(text))
			{
				string[] words = text.Split(' ');
				if (!words.IsNullOrEmpty())
				{
					foreach (string word in words)
					{
						string first = word.Substring(0, 1);
						result += first.ToUpperInvariant() + word.Substring(1) + " ";
					}
					result = result.Trim();
				}
			}

			return result;
		}

		public static string FitSize(this string text, int pixels, Font font, string addAfter)
		{
			Label label = new Label();

			Graphics g = label.CreateGraphics();  // Create the graphics for this label
			SizeF w;                         // Size object to be used for calculating
			float available = pixels - 1;    // Adjust the available pixels to handle whitespace
			bool isTruncated = false;       // Assume the string will fit
			string result = string.Empty;    // Will contain the result for this method
			
			// When there is no font specified, assign the label font as the font to be used
			if (font == null)
				font = label.Font;

			// When an AddAfter text was specified, calculate the length of
			// that text and adjust the available white space
			if (addAfter.Trim().Length > 0) available -= g.MeasureString(addAfter.Trim(), font).Width;

			// If there is room to fit the string
			if (available > 0)
			{
				// Now assign the text to the result
				result = text;

				do
				{
					// Calculate the width of the Result string using the specified font
					w = g.MeasureString(result, font);

					// If there aren't enough pixels available, truncate the string
					if (w.Width > available)
					{
						result = result.Substring(0, (int)((result.Length * available) / w.Width));

						isTruncated = true;
					}
				} while (w.Width > available);

				// If the string was truncated, we need to add the AddAfter string if
				// there was one specified
				if (isTruncated && (addAfter.Trim().Length > 0))
					result += addAfter.Trim();
			}
			return result;
		}
	}
}
